//
//  UserAccount.swift
//  微博Swift
//
//  Created by  justinchou on 16/2/25.
//  Copyright © 2016年  justinchou. All rights reserved.
//

import UIKit

private let JustinUserAccountKey = "me.love.userAccount"

class UserAccount: NSObject {
    
    //设置单例
    static let sharedUserAccount = UserAccount()
    
    
    /// 判断是否登录标记
    var isLogin: Bool {
        return access_token != nil
    }
    
    /// 用于调用access_token，接口获取授权后的access token
    var access_token: String?
    /// 当前授权用户的UID
    var uid: String?
    
    /// expireData 过期日期
    var expireData: NSDate?
    /// access_token的生命周期，单位是秒数
    var expires_in: NSTimeInterval = 0 {
        didSet{
            expireData = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    
    
    private override init() {
        super.init()
        
        //加载用户信息,使用UserAccount.sharedUserAccount时就已经将数据拿出来
        loadUserAccount()
    }
    
    // MARK:- 一定要重写 否则会崩溃遇到没有key的值
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
    
    
    //帮助测试开始，需要写！
    override var description: String {
        
        let keys = ["access_token", "uid", "expires_in", "expireData", "screen_name", "avatar_large"]
        
        return dictionaryWithValuesForKeys(keys).description
    }
    
    
}

extension UserAccount {
    
    /// 保存用户信息
    func saveUserAccount() {
        
        let keys = ["access_token", "uid", "expireData", "screen_name", "avatar_large"]
        
        let dict = dictionaryWithValuesForKeys(keys)
        
        NSUserDefaults.standardUserDefaults().setObject(dict, forKey: JustinUserAccountKey)
        print("保存用户账户 \(NSHomeDirectory())")
    }
    
    private var isExpired: Bool {
        return expireData?.compare(NSDate()) == NSComparisonResult.OrderedAscending
    }
    
    //加载用户信息
    private func loadUserAccount() {
        
        guard let dict = NSUserDefaults.standardUserDefaults().valueForKey(JustinUserAccountKey) as? [String: AnyObject] else {
            return
        }
        
        //设置属性
        setValuesForKeysWithDictionary(dict)
        
        if isExpired {
            access_token = nil
        }
    }
    
    //更新用户账户
    func updateUserAccount(dict: [String: AnyObject]) {
        
        setValuesForKeysWithDictionary(dict)
        
        saveUserAccount()
    }
    
}




